package wiki;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.Root;

/**
 * Servlet implementation class GetDataForChart
 */
public class GetDataForChart extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetDataForChart() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();

		Root root = new Root();
		ResultSet rs = null;
		PreparedStatement pst = null;
		JSONObject section = null;
		JSONArray sectionlist = null;
		JSONObject chartdata = new JSONObject();

		try {

			String module = "";

			// action = request.getParameter("action");

			String sql = "";
			sectionlist = new JSONArray();
			// System.out.println("Version: " + version);

			root.initConnection();
			sql = " SELECT s.id, s.sectionname, count(i.moduleid) as count FROM sections s "
					+ " left join issue i on  s.id=i.moduleid  where s.parentid =0 GROUP BY s.id";
			pst = root.con.prepareStatement(sql);
			System.out.println("SQL" + pst);
			rs = pst.executeQuery();

			while (rs.next()) {
				JSONArray allsections = new JSONArray();
				allsections.add(rs.getString("sectionname"));
				allsections.add(rs.getString("count"));
				sectionlist.add(allsections);
			}

			
			chartdata.put("chartdata", sectionlist.toString());
			//System.out.println("Section" + sectionlist.toString());
			
		} catch (Exception e) {
			System.out.println("Exception :" + e.toString());
		} finally {
			try {
				pst.close();
				rs.close();
				root.closeConnection();
			} catch (Exception e) {

			}
		}
		
		out.println(chartdata.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
